<template>
  <!-- 只显示未隐藏的菜单项 -->
  <div v-if="!isHidden">
    <!-- 没有子菜单的情况：直接显示菜单项 -->
    <el-menu-item v-if="!hasChildren" :index="fullPath" :route="fullPath">
      <el-icon v-if="item.meta && item.meta.icon">
        <component :is="item.meta.icon" />
      </el-icon>
      <template #title>
        <span>{{ item.meta && item.meta.title }}</span>
      </template>
    </el-menu-item>

    <!-- 有子菜单的情况：显示子菜单 -->
    <el-sub-menu v-else :index="fullPath" popper-append-to-body>
      <template #title>
        <el-icon v-if="item.meta && item.meta.icon">
          <component :is="item.meta.icon" />
        </el-icon>
        <span>{{ item.meta && item.meta.title }}</span>
      </template>

      <!-- 递归渲染子菜单 -->
      <menu-item
        v-for="child in visibleChildren"
        :key="child.path"
        :item="child"
        :parent-path="fullPath"
      />
    </el-sub-menu>
  </div>
</template>

<script setup lang="ts">
import { computed } from 'vue';
import { RouteRecordRaw } from 'vue-router';

interface Props {
  item: RouteRecordRaw;
  parentPath?: string;
}

const props = withDefaults(defineProps<Props>(), {
  parentPath: ''
});

// 计算完整路径
const fullPath = computed(() => {
  const { path } = props.item;

  // 如果路径以 / 开头，说明是绝对路径，直接返回
  if (path.startsWith('/')) {
    return path;
  }

  // 否则拼接父路径
  const parentPath = props.parentPath || '';
  if (parentPath.endsWith('/')) {
    return parentPath + path;
  } else {
    return parentPath + '/' + path;
  }
});

// 判断是否隐藏
const isHidden = computed(() => {
  return props.item.meta && props.item.meta.isHidden;
});

// 获取可见的子路由
const visibleChildren = computed(() => {
  if (!props.item.children) return [];
  return props.item.children.filter(child => !child.meta || !child.meta.isHidden);
});

// 判断是否有子菜单
const hasChildren = computed(() => {
  return visibleChildren.value.length > 0;
});
</script>

<style lang="scss" scoped>
.text {
  font-size: 14px;
}

// 菜单项高亮样式
:deep(.el-menu-item) {
  &.is-active {
    background: linear-gradient(
      270deg,
      rgba(57, 120, 233, 0.2) 0%,
      rgba(57, 120, 233, 0.05) 100%
    ) !important;
    border-right: 4px solid var(--theme-color-primary);
    color: var(--theme-color-primary) !important;
  }
}

// 子菜单展开时的样式
:deep(.el-sub-menu) {
  &.is-opened {
    > .el-sub-menu__title {
      color: var(--theme-color-primary) !important;
    }
  }
}

// 暗色主题下的样式
:root[data-theme='dark'] {
  :deep(.el-menu-item.is-active) {
    background: linear-gradient(
      270deg,
      rgba(75, 180, 255, 0.2) 0%,
      rgba(75, 180, 255, 0.05) 100%
    ) !important;
    border-right-color: var(--theme-color-primary);
  }

  :deep(.el-sub-menu.is-opened > .el-sub-menu__title) {
    color: var(--theme-color-primary-dark) !important;
  }
}
</style>
